<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item>
        <el-input v-model="queryParams.title" placeholder="请输入职称名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row v-if="checkPermission(['admin','user'])" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="dialogVisible = true, operationType = 'add'">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini">批量删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog title="编辑信息" :visible.sync="dialogVisible" width="30%" append-to-body>
      <el-form ref="form" :model="titleinfo" :rules="rules" label-width="120px">
        <el-form-item label="职称" prop="title">
          <el-input v-model="titleinfo.title" style="width: 73.5%;" />
        </el-form-item>
        <el-form-item label="获取时间" prop="obtainDate">
          <el-date-picker v-model="titleinfo.obtainDate" type="date" placeholder="请选择获取时间" />
        </el-form-item>
        <el-form-item style="margin-left: 5%">
          <el-button type="primary" @click="add()">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <!--      <el-table-column type="selection" style="width: 50px" />-->
      <el-table-column prop="title" label="职称名称" align="center" />
      <el-table-column prop="obtainDate" label="获取时间" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column v-if="checkPermission(['admin','user'])" label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-edit" @click="update(scope.row.id), operationType = 'update'">修改</el-button>
          <el-button size="small" type="text" icon="el-icon-delete" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils'
import { add, update, deleteById, selectById, pageUsingPost } from '@/api/Title'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { deptTreeSelect } from '@/api/user'
import checkPermission from '@/utils/permission'

export default {
  data() {
    return {
      operationType: 'add', // 操作类型，默认是新增
      deptOptions: undefined,
      titleinfo: {
        title: '',
        obtainDate: '', // 获取时间
        userId: this.userId,
        id: this.currentId
      },
      value: '',
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      avatar:
        'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      queryParams: {
        title: '',
        obtainDate: '' // 获取时间
      },
      major: {
        name: ''
      },
      rules: {
        title: [{ required: true, message: '职称不能为空', trigger: 'blur' }],
        obtainDate: [{ required: true, message: '获取时间不能为空', trigger: 'blur' }]
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址B
        url: process.env.VUE_APP_BASE_API + 'user/excel-input'

      },
      multipleSelection: [],
      filename: '',
      tableData: [],
      list: undefined,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      userId: ''
    }
  },
  created() {
    this.userId = this.$route.params.id
    this.getDeptTree()
  },
  mounted() {
    this.userId = this.$route.params.id
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },
  methods: {
    checkPermission,
    handleClose() {
      this.dialogVisible = false
      this.major = { name: '', type: '', parentId: '' }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 查询分页数据
    page() {
      const requestData = {
        title: this.queryParams.title,
        obtainDate: this.queryParams.obtainDate,
        pageSize: this.pageSize,
        userId: this.userId
      }
      pageUsingPost(requestData)
        .then((res) => {
          console.log('requestData', requestData)

          this.totalCount = res.data.total
          console.log('res', res)

          this.tableData = res.data.records
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },
    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 导出按钮操作 */
    handleExport() {
      // 选中数据时下载选择数据
      if (this.multipleSelection.length > 0) {
        this.queryParams.ids = this.multipleSelection.map((item) => item.id) // 传递筛选后的id数组
        this.filename = '选中教师-' + new Date().getTime() + '.xlsx'
        // eslint-disable-next-line no-empty
      } else {
        this.queryParams.ids = [] // 传递空数组
        if (this.queryParams.name === '' && this.queryParams.number === '' && this.queryParams.phoneNumber === '' && this.queryParams.email === '') {
          this.filename = '全部教师-' + new Date().getTime() + '.xlsx'
          // eslint-disable-next-line no-empty
        } else {
          this.filename = '筛选教师-' + new Date().getTime() + '.xlsx'
        }
      }
      this.download(process.env.VUE_APP_BASE_API + '/user/excel-output', this.queryParams, this.filename)
      // this.download(process.env.VUE_APP_BASE_API + '/user/excel-output', this.queryParams, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(process.env.VUE_APP_BASE_API + '/user/template', {
      }, `教师信息模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg ? response.msg : response.data + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },

    clear() {
      this.queryParams = { number: '', name: '', phoneNumber: '' }
      this.page()
    },
    // 添加数据
    add() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let operator
          this.titleinfo.userId = this.userId
          this.titleinfo.id = this.currentId
          console.log('this.titleinfo', this.titleinfo)

          if (this.operationType === 'update') {
            operator = update(this.titleinfo)
          } else if (this.operationType === 'add') {
            operator = add(this.titleinfo)
          } else {
            console.error('未知的操作类型:', this.operationType)
            return
          }

          operator.then((resp) => {
            console.log('API 响应:', resp)
            if (resp.code == '1') {
              this.dialogVisible = false // 关闭对话框
              this.$message({ message: '恭喜你，保存成功', type: 'success' })
              // 新增操作时重置表单
              if (this.operationType === 'add') {
                this.$refs['form'].resetFields()
              }
              this.page() // 刷新页面数据
            } else {
              this.$message.error(resp.msg) // 显示错误信息
            }
          }).catch((error) => {
            console.error('接口请求错误:', error)
            this.$message.error('请求失败，请稍后重试')
          })
        } else {
          console.error('表单验证失败')
        }
      })
    },

    update(id) {
      this.dialogVisible = true
      this.currentId = id

      selectById(id).then((result) => {
        if (result.code === 1) {
          this.titleinfo = result.data
        } else {
          this.$message.error('获取职称信息失败')
        }
      }).catch((error) => {
        this.$message.error('请求失败，请稍后重试')
        console.error('接口请求错误:', error)
      })
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    // 删除员工信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 构造请求参数
          const requestData = { id } // 这里构造传递给后端的请求数据

          // 发送删除请求
          deleteById(requestData).then((resp) => {
            if (resp.code === 1) {
              // 删除成功
              this.$message.success('恭喜你，删除成功')
              this.page() // 刷新页面
            } else {
              this.$message.error(resp.msg)
            }
          })
            .catch((error) => {
              this.$message.error('请求失败，请稍后重试')
              console.error('删除失败:', error)
            })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },

    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
